package xq.gwt.ui.crud;
import xq.gwt.mvc.model.BooleanPropertyModel;
import xq.gwt.mvc.model.CommandModel;
import xq.gwt.mvc.model.PersistableEntityModel;
import xq.gwt.ui.crud.localization.CrudDictionary;
import xq.gwt.ui.rpc.AsyncCallbackAdapter;
import xq.gwt.ui.widgets.feedback.DefaultFeedbackPresenter;

import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;

public class DeleteEntityCommand implements CommandModel{
		
	private static final long serialVersionUID = -5735770114466978242L;
	private BooleanPropertyModel enabled = new BooleanPropertyModel();
	private PersistableEntityModel persistableEntity;
	private PersistableEntityModel persistableEntityDTO;
	private String feedBack = null;
	private EntityEditorModel editorModel;

	public DeleteEntityCommand(EntityEditorModel editorModel){
		this.editorModel = editorModel;
		updateEnabled();
	}
	
	@Override
	public void execute() throws Exception {
		feedBack = null;
		persistableEntityDTO = persistableEntity.copy();
		SC.confirm(CrudDictionary.Constants().confirmDelete_msg(), new BooleanCallback() {  
			                     public void execute(Boolean value) {  
			                         if (value != null && value) {  
			                             deleteEntity();  
			                         } else {  
			                             return;  
			                         }  
			                     }  
			                 });		
		
		
	}

	private void deleteEntity(){		
		CrudServiceProvider.persistanceService.deleteEntity(persistableEntityDTO, new EntityDeletedCallback());
	}
	
	private class EntityDeletedCallback extends AsyncCallbackAdapter<Boolean>{
		@Override
		public void onSuccess(Boolean result) {
			DefaultFeedbackPresenter presenter = new DefaultFeedbackPresenter();
			presenter.showFeedback(CrudDictionary.Constants().entityDeleted_msg());				
			editorModel.setEntity(null);
		}				
	}
	
	public void setEntity(PersistableEntityModel persistableEntity){
		this.persistableEntity = persistableEntity;
		updateEnabled();
	}
	
	@Override
	public String getCaption() {		
		return CrudDictionary.Constants().delete_caption();
	}

	@Override
	public String getName() {		
		return "Delete";
	}

	private void updateEnabled(){
		if(persistableEntity == null){
			enabled.setValue(false);
		}
		else{
			enabled.setValue(true);
		}
		
	}
	
	@Override
	public BooleanPropertyModel isEnabled() {		
		return enabled;
	}

	@Override
	public String getFeedback() {		
		return feedBack;
	}

}
